﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;
using MailKit.Security;

namespace TimerTask.Common.Utils
{
    public class EmailUtil
    {
        public static async Task SendEmailAsync(string toMail, string subject, string message)
        {
            LogUtil.Error("[2]发邮件开始...");
            if (toMail.IsNull() || subject.IsNull() || message.IsNull())
            {
                throw new ArgumentException("传递参数有误！");
            }
            List<string> mails = new List<string>();

            if (toMail.Contains(","))
            {
                foreach (var s in toMail.Split(','))
                {
                    mails.Add(s);
                }
            }
            else
            {
                mails.Add(toMail);
            }
            var emailMessage = new MimeMessage();

            foreach (var mail in mails)
            {
                emailMessage.To.Add(new MailboxAddress("", mail));
            }
            emailMessage.From.Add(new MailboxAddress("", AppConfig.Instance.EmailNotify.UserName));

            emailMessage.Subject = subject;

            emailMessage.Body = new TextPart("plain") { Text = message };

            using (var client = new SmtpClient())
            {
                client.LocalDomain = AppConfig.Instance.EmailNotify.LocalDomain;

                var credentials = new NetworkCredential
                {
                    UserName = AppConfig.Instance.EmailNotify.UserName, // replace with valid value
                    Password = AppConfig.Instance.EmailNotify.GetPwd()  // replace with valid value
                };
                await client.ConnectAsync(AppConfig.Instance.EmailNotify.Smtp, 25, SecureSocketOptions.None).ConfigureAwait(false);
                await client.AuthenticateAsync(credentials);
                await client.SendAsync(emailMessage).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
                LogUtil.Error("[2]发邮件结束...", "Email");
            }
        }
    }
}